package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.SeckillWebIntereptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSessionTo;
import com.atguigu.gulimall.seckill.to.SkuInfoTo;
import com.atguigu.gulimall.seckill.to.SkuSkillRedisTo;
import com.atguigu.gulimall.seckill.to.SkuSkillTo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;


import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skukill:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    /**
     * 上架最近三天的秒杀活动以及秒杀商品
     */
    @Override
    public void uploadloadLates3() {
        R r = couponFeignService.listLatest3Day();
        if (r.getCode() == 0) {
            //查询最近三天的秒杀商品
            List<SeckillSessionTo> data = r.getData(new TypeReference<List<SeckillSessionTo>>() {
            });
            //缓存秒杀场次信息
            cacheSession(data);
            //缓存秒杀商品信息
            cacheSkuskill(data);
            //缓存商品详细信息
        }
    }

    /**
     * 查询当前时间的秒杀商品
     * @return
     */
    @Override
    public List<SkuSkillRedisTo> querySkuskillLatest() {
        //查询当前时间的秒杀场次
        Set<String> keys = redisTemplate.keys("seckill:sessions:**");
        for (String key : keys) {
            String replace = key.replace("seckill:sessions:", "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            long now = new Date().getTime();
            if(now>=start&&now<=end){
                //说明当前时间存在该秒杀活动
                //查出所有秒杀商品
                List<String> skuids = redisTemplate.opsForList().range(key, -100, 100);//取出该集合所有的商品id
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(skuids);
                if(list!=null&&list.size()>0){
                    List<SkuSkillRedisTo> collect = list.stream().map(item -> {
                        SkuSkillRedisTo redisTo = JSON.parseObject(item, SkuSkillRedisTo.class);
//                        redisTo.setRandomCode(null); //若为预发布，则不能返回随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
        //查询秒杀商品

    }

    /**
     * 根据skuid查询秒杀信息
     * @param skuId
     * @return
     */
    @Override
    public SkuSkillRedisTo seckillSku(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        String regex = "\\d_"+skuId;
        for (String key : keys) {
            if(Pattern.matches(regex,key)){
                String s = hashOps.get(key);
                SkuSkillRedisTo redisTo = JSON.parseObject(s, SkuSkillRedisTo.class);
                //判断当前商品是否正在秒杀
                long now = new Date().getTime();
                if(now>=redisTo.getStartTime()&&now<=redisTo.getEndTime()){

                }else{
                    //不在秒杀期间，屏蔽随机码
                    redisTo.setRandomCode(null);
                }
                return redisTo;
            }
        }
        return null;
    }

    @Override
    public String kill(String skuId, Integer num, String key) {
        long s = System.currentTimeMillis();
        //合法性校验
        //查询当前秒杀商品
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(skuId);
        if(StringUtils.isNotEmpty(json)){
            SkuSkillRedisTo redisTo = JSON.parseObject(json, SkuSkillRedisTo.class);
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            long now = new Date().getTime();
            long ttl = endTime - now;
            //1.验证秒杀时间
            if(now>=startTime&&now<=endTime){
                //2.随机码和商品id
                String sku  = redisTo.getPromotionSessionId()+"_"+ redisTo.getSkuId();
                String randomCode = redisTo.getRandomCode();
                //3.秒杀数量限制关系
                Integer seckillLimit = redisTo.getSeckillLimit().intValue();
                if(num<=seckillLimit){
                    if(key.equals(randomCode)&&skuId.equals(sku)){
                        //4.幂等性(防止脚本重复秒杀，每个人只能秒杀一次,成功后去redis占坑，下次再去判断是否有坑(使用userid加商品id作为key))
                        MemberVo memberVo = SeckillWebIntereptor.loginUser.get();
                        Long userId = memberVo.getId();
                        String redisKey = userId+"_"+skuId;
                        Boolean absent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(),ttl,TimeUnit.MILLISECONDS);//活动过期自动过期
                        if(absent){
                            //说明以前没有购买
                            //秒杀成功，扣减信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + key);
                            try {
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);//每个请求最多阻塞100ms，超过100ms自动释放锁
                                if(b){
                                    //生成订单号
                                    String orderSn = IdWorker.getTimeId();
                                    //给订单服务发送消息（流量削峰）
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    orderTo.setOrderSn(orderSn);
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    orderTo.setMemberId(memberVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);
                                    long e = System.currentTimeMillis();
                                    System.out.println(s-e);
                                    return orderSn;
                                }
                                else {
                                    return null;
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }


                        }
                        else {
                            return null;
                        }
                    }
                    else {
                        return null;
                    }
                }
                else{
                    return null;
                }
            }else{
                return null;
            }
        }else{
            return null;
        }
        return null;
    }

    /**
     * 缓存秒杀场次信息
     * key:开始时间_结束时间
     * value:秒杀商品id集合
     *
     * @param data
     */
    private void cacheSkuskill(List<SeckillSessionTo> data) {
        data.stream().map(session -> {
            Long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + "_" + endTime;
            if (!redisTemplate.hasKey(key)) {
                List<SkuSkillTo> skuSkill = session.getSkuSkill();
                List<String> skuIds = skuSkill.stream().map(sku -> session.getId() + "_" + sku.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
            return session;
        }).collect(Collectors.toList());
    }

    /**
     * 缓存秒杀商品信息
     * key:skuId
     * value:秒杀商品对象，以及该商品的详细信息
     *
     * @param data
     */
    private void cacheSession(List<SeckillSessionTo> data) {
        data.stream().map(session -> {
            List<SkuSkillTo> skuSkill = session.getSkuSkill();
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            skuSkill.stream().map(sku -> {
                String key = session.getId().toString() + "_" + sku.getSkuId().toString();
                if (!hashOps.hasKey(key)) {
                    SkuSkillRedisTo skillRedisTo = new SkuSkillRedisTo();
                    //1.秒杀信息
                    BeanUtils.copyProperties(sku, skillRedisTo);
                    //2.查询sku详细信息
                    R r = productFeignService.skuInfo(sku.getSkuId());
                    if (r.getCode() == 0) {
                        skillRedisTo.setSkuInfo(r.getData("skuInfo", new TypeReference<SkuInfoTo>() {
                        }));
                    }
                    //3.商品开始和结束时间
                    skillRedisTo.setStartTime(session.getStartTime().getTime());
                    skillRedisTo.setEndTime(session.getEndTime().getTime());
                    //4.随机码（防止恶意刷单）
                    String token = UUID.randomUUID().toString().replace("-", "");
                    skillRedisTo.setRandomCode(token);
                    //5.使用分布式信号量（限流）
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(sku.getSeckillCount().intValue());
                    String s = JSON.toJSONString(skillRedisTo);
                    hashOps.put(key, s);
                }
                return sku;
            }).collect(Collectors.toList());
            return session;
        }).collect(Collectors.toList());
    }
}
